<template>
  <el-drawer
	v-model="dialog.visible"
	:title="dialog.title"
    size="750"
    destroy-on-close
	@close="closeDialog"
	:close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
      class="drawer-form"
    >
	<el-scrollbar >
	<div style="margin-bottom: 18px;">
		<span class="title-form_primary">基础信息</span>
	</div>	
	
      <el-form-item label="SQL名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入SQL名称" />
      </el-form-item>
	  
	  <el-form-item label="SQL标识" prop="identifier">
	    <el-input v-model="formData.identifier" placeholder="请输入SQL标识" />
	  </el-form-item>
	  
	  <el-form-item label="SQL类型" prop="type">
	    <el-radio-group v-model="formData.type" class="flex-container">
	      <el-radio value="InfluxDB">InfluxDB</el-radio>
	      <el-radio value="normal">常规SQL</el-radio>
	    </el-radio-group>
	  </el-form-item>
	  
	  <el-form-item label="SQL执行" prop="exec">
	  		 <Dict v-model="formData.exec" code="sql_execute_type" @change="handleExecChange"/>
	  </el-form-item>
	  
	  <el-form-item label="SQL表名" prop="table" v-if="['save','update'].includes(formData.exec)">
	    <el-input v-model="formData.table" placeholder="请输入SQL表名" />
	  </el-form-item>
	  
	  <el-form-item label="SQL主键" prop="primaryKey" v-if="['save','update'].includes(formData.exec)">
	    <el-input v-model="formData.primaryKey" placeholder="请输入SQL主键" />
	  </el-form-item>
	  
      <el-form-item label="SQL类别" prop="categoryId">
		<el-tree-select
			v-model="formData.categoryId"
			placeholder="请选择SQL类别"
			:data="categoryList"
			filterable
			check-strictly
			:render-after-expand="false"
			:props="defaultProps"
		/>
      </el-form-item>
      
      <el-form-item label="数据源" prop="datasourceId">
        <el-select v-model="formData.datasourceId" placeholder="请选择数据源" style="width: 100%">
          <el-option
            v-for="item in datasourceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
	  
	  <el-form-item label="排序号" prop="sort">
	    <el-input-number v-model="formData.sort" :min="0" :max="9999" />
	  </el-form-item>
	  
		<div style="margin-bottom: 18px;">
			<span class="title-form_primary">SQL参数</span>
			<el-button 
			  type="primary" 
			  link
			  @click="handleAddParam"
			  style="margin-left: 12px;"
			>
			  <el-icon><Plus /></el-icon>添加参数
			</el-button>
		</div>
	
		<div class="sql-param-content">
			<el-table 
			  :data="paramField" 
			  style="width: 100%"
			  border
			>
			  <el-table-column prop="name" label="参数名称" />
			  <el-table-column prop="identifier" label="参数标识" />
			  <el-table-column prop="type" label="参数类型"></el-table-column>
			  <el-table-column prop="required" label="必填" width="80">
				<template #default="{ row }">
				  <el-tag :type="row.required=='1' ? 'danger' : 'info'" size="small">
					{{ row.required=='1' ? '是' : '否' }}
				  </el-tag>
				</template>
			  </el-table-column>
			  <el-table-column label="操作" width="150" fixed="right">
				<template #default="scope">
				  <el-button 
					link 
					type="primary" 
					@click="handleEditParam(scope.row, scope.$index)"
				  >编辑</el-button>
				  <el-button 
					link 
					type="danger" 
					@click="handleDeleteParam(scope.$index)"
				  >删除</el-button>
				</template>
			  </el-table-column>
			</el-table>
		</div>
	  
		<div style="margin-bottom: 18px;" v-if="!['save','update'].includes(formData.exec)">
			<span class="title-form_primary">SQL语句</span>
		</div>	
	  
      <el-form-item prop="sql" class="sql-editor" v-if="!['save','update'].includes(formData.exec)">
		  <div  style="margin-left: 0px;background-color: red;width: 100%;">
			  <MonacoEditor
			    v-model="sqlcontent"
			    :options="monacoOptions"
			    @change="handleEditorChange"
				 style="height: 220px;"
			  />
		  </div>
      </el-form-item>
	  </el-scrollbar>
    </el-form>
    
    <template #footer>
      <el-button @click="closeDialog" :loading="loading">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>

    <!-- SQL参数编辑抽屉 -->
    <EditParamFieldDrawer
      ref="editParamFieldDrawerRef"
      @success="handleParamSuccess"
    />
  </el-drawer>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue';
	import type { FormInstance } from 'element-plus';
	import SqlAPI from '@/api/biz/sql';
	import DatasourceAPI from '@/api/biz/datasource';
	import {recurOptions} from "@/utils/TreeUtil";
	import EditParamFieldDrawer from '@/components/DataWorkflow/components/EditParamFieldDrawer.vue';
	import MonacoEditor from '@/components/MonacoEditor/index.vue'
	import { ElMessageBox } from 'element-plus';
	
	const emit = defineEmits(['closeDialog']);
	const formRef = ref<FormInstance>();
	const loading = ref(false);
	const dialog = ref({
		visible: false,
		title: '',
	});
	const formData = ref<any>();
	const paramField=ref<any[]>([]);

	// Monaco Editor 配置
	const monacoOptions = ref({
		theme: 'vs-dark',
		language: 'sql',
		readOnly: false,
		automaticLayout: true,
		scrollBeyondLastLine: true,
		minimap: { enabled: false },
		lineNumbers: 'on',
		folding: true,
		wordWrap: 'on',
		fontSize: 14,
		tabSize: 2,
		suggestOnTriggerCharacters: true,
		formatOnPaste: true,
		formatOnType: true,
		suggest: {
			preview: true,
			showWords: true,
			showSnippets: true
		},
		contextmenu: true
	});

	const rules = {
	  name: [{ required: true, message: '请输入SQL名称', trigger: 'blur' }],
	  identifier: [{ required: true, message: '请输入SQL标识', trigger: 'blur' }],
	  exec: [{ required: true, message: '请输入SQL执行', trigger: 'blur' }],
	  categoryId: [{ required: true, message: '请选择所属类别', trigger: 'change' }],
	  datasourceId: [{ required: true, message: '请选择数据源', trigger: 'change' }],
	  type: [{ required: true, message: '请选择SQL类型', trigger: 'blur' }],
	  sqlcontent: [{ required: true, message: '请输入SQL语句', trigger: 'blur' }],
	  table: [{ required: true, message: '请输入SQL表名称', trigger: 'blur' }],
	  primaryKey: [{ required: true, message: '请输入SQL主键', trigger: 'blur' }],
	};


	const categoryList = ref<any[]>();
	const datasourceList = ref<any[]>([]);
	const defaultProps = {
	  children: 'children',
	  label: 'name',
	  value:'id'
	}
	const getCategoryList = async () => {
	  const res = await SqlAPI.getCategoryList({ keywords: '' });
	  categoryList.value = recurOptions(res,'');
	};

	// 获取数据源列表
	const getDatasourceList = async () => {
	  const res = await DatasourceAPI.options({});
	  datasourceList.value = res;
	};

	const handleExecChange = () => {
	//	console.log(formData.type)
	};

	// 编辑器内容变化
	const handleEditorChange = (value: string) => {
	  formData.value.sql = value;
	};

	const editParamFieldDrawerRef = ref();

	// 添加参数
	const handleAddParam = () => {
	   editParamFieldDrawerRef.value?.openDialog(-1,null,'add',true);
	};

	// 编辑参数
	const handleEditParam = (row: any, index: number) => {
	  editParamFieldDrawerRef.value?.openDialog(index,row,'edit',true);
	};

	// 删除参数
	const handleDeleteParam = (index: number) => {
	  ElMessageBox.confirm('确认要删除该参数吗？', '警告', {
		type: 'warning'
	  }).then(() => {
		paramField.value.splice(index, 1);
	  });
	};

	// 参数保存成功回调
	const handleParamSuccess = (index:number,param: any) => {
	  if (index === -1) {
		paramField.value.push(param);
	  } else {
		paramField.value[index] = param;
	  }
	};

	const sqlcontent=ref<string>("");
	async function openDialog(row?: any, type?: string) {
		dialog.value = {
			visible: true,
			title: type === 'add' ? '新增SQL' : '编辑SQL'
		};
		getCategoryList();
		getDatasourceList();
		if (type === 'add') {
			formData.value={};
			paramField.value = [];
		}else{
			formData.value=row;
			if(formData.value.content){
				const content=JSON.parse(formData.value.content);
				if(content){
					sqlcontent.value=content.sql;
					paramField.value=content.params || [];
					return;
				}
			}
			paramField.value = [];
			sqlcontent.value="";
		}
	}

	const handleSubmit = async () => {
	  await formRef.value?.validate();
	  try {
		loading.value = true;
		formData.value.content=JSON.stringify({
			sql:sqlcontent.value,
			params:paramField.value
		});
		
		console.log(formData.value);
		
		await SqlAPI.save(formData.value);
		closeDialog();
	  } finally {
		loading.value = false;
	  }
	};

	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emit('closeDialog')
		resetForm();
	}
	/**
	 * 重置表单
	 */
	function resetForm() {
		formRef.value?.resetFields();
		formRef.value?.clearValidate();
		formData.value={};
		paramField.value = [];
		sqlcontent.value="";
	}
	
	defineExpose({
	  openDialog,closeDialog
	});

	onMounted(() => {
	});
</script>

<style lang="scss" scoped>
	.drawer-form {
		padding: 20px;
		height: calc(100vh - 120px);
		overflow-y: auto;
	}

	.sql-editor-item {
		height: 400px;
		display: flex;
		flex-direction: column;

		.editor-toolbar {
			margin-bottom: 8px;
		}

		.editor-container {
			border: 1px solid var(--el-border-color);
			border-radius: 4px;
			width: 100%;
		}

		:deep(.monaco-editor) {
			height: 100% !important;
		}
	}

	.title-form_primary {
		font-style: normal;
		font-weight: 500;
		font-size: 14px;
		color: #1f2329;
		position: relative;
		padding-left: 5px;
	}
	
	.title-form_primary:before {
	    content: "";
	    width: 2px;
	    height: 14px;
	    background: var(--el-color-primary);
	    position: absolute;
	    top: 50%;
	    transform: translateY(-50%);
	    left: 0;
	}
	
	.sql-param-content {
	  margin-bottom: 20px;
	  
	  .el-table {
		margin-top: 12px;
	  }
	}

	.param-actions {
	  display: flex;
	  justify-content: flex-end;
	  margin-bottom: 12px;
	}
	
	.sql-editor{
		:deep(.el-form-item__content) {
			margin-left: 0px !important;
		}
	}
</style> 